package com.cloud.base.reflection;

import lombok.SneakyThrows;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Main {
    @SneakyThrows
    public static void main(String[] args) {
        // 反射
        Main.test1();
        Main.test2();
        Main.test3();

        //创建反射类对象
        // 无参构造函数
        Class<?> aClass = Class.forName("com.cloud.base.reflection.DemoReflection");
        DemoReflection demo = (DemoReflection) aClass.newInstance();
        //  有参构造函数
        Class<?> aClass1 = Class.forName("com.cloud.base.reflection.DemoReflection");
        Constructor<?> constructor = aClass1.getConstructor(String.class, int.class);
        DemoReflection demo1 = (DemoReflection) constructor.newInstance("张三", 18);
        System.out.println(demo1);
        System.out.println(demo);
    }

    @SneakyThrows
    private static void test1() {
        DemoReflection demo = new DemoReflection();
        Class<? extends DemoReflection> aClass = demo.getClass();
        DemoReflection demo1 = aClass.newInstance();
        Method me = aClass.getDeclaredMethod("show", new Class[]{String.class});
        me.setAccessible(true);
        Object str = me.invoke(demo1, new Object[]{"张三"});
        System.out.println(str);
    }

    @SneakyThrows
    private static void test2() {
        Class<? extends DemoReflection> aClass = DemoReflection.class;
        DemoReflection demo1 = aClass.newInstance();
        Method me = aClass.getDeclaredMethod("show", new Class[]{String.class});
        me.setAccessible(true);
        Object str = me.invoke(demo1, new Object[]{"李四"});
        System.out.println(str);
    }

    @SneakyThrows
    private static void test3() {
        Class<?> aClass = Class.forName("com.cloud.base.reflection.DemoReflection");
        DemoReflection demo1 = (DemoReflection) aClass.newInstance();
        Method me = aClass.getDeclaredMethod("show", new Class[]{String.class});
        me.setAccessible(true);
        Object str = me.invoke(demo1, new Object[]{"王五"});
        System.out.println(str);
    }
}
